import React, { FC, ReactElement, useRef } from 'react';
import { ITodo } from '../../../typings';

interface IProps {
  addTodo: (todo: ITodo) => void;
  todoList: ITodo[];
}

const TdInput: FC<IProps> = ({ addTodo, todoList }): ReactElement => {
  //useRef/useState等hooks后面应该加一个泛型
  const inputRef = useRef<HTMLInputElement>(null);

  const addItem = (): void => {
    //从inputRef拿到DOM里的值(确定得到)
    const val: string = inputRef.current!.value.trim();

    //有值时
    if (val.length) {
      const isExist = todoList.find((todo) => todo.content === val);

      //找到匹配内容时说明重复
      if (isExist) {
        alert('已经存在该项');
        return;
      }

      //没有重复时新增
      addTodo({
        id: new Date().getTime(),
        content: val,
        completed: false
      });

      //清空输入框文本内容
      inputRef.current!.value = '';
    }
  };

  return (
    <div className="todo-input">
      <input type="text" placeholder="请输入待办事项" ref={inputRef} />
      <button onClick={addItem}>增加</button>
    </div>
  );
};

export default TdInput;
